<?php

//use JPush\Config;

use think\Config;
use think\Loader;
use think\Request;


function p($array){
    dump($array,1,'<pre>',0);die;
}

function changeGoodsNum($id,$type){
    $res = \think\Db::name('product')->field('category_id,type_id,small_type_id')->where('id',$id)->find();
    $ids = [$res['category_id'],$res['type_id'],$res['small_type_id']];
    if($type==1){
        $res = \think\Db::name('base_data')->whereIn('id',$ids)->setInc('goods_num');
    }else{
        $res = \think\Db::name('base_data')->whereIn('id',$ids)->setDec('goods_num');
    }
    return true;
}

//随机数字
function getRndNumber($length) {
    $pattern = '1234567890';
    $key = '';
    for ($i = 0; $i < $length; $i++) {
        $key .= $pattern{mt_rand(0, 9)};
    }
    return $key;
}
//随机字符串
function getRndString($length) {
    $pattern = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    $key = '';
    for ($i = 0; $i < $length; $i++) {
        $at = mt_rand(0, 61);
        $key .= $pattern{$at};
    }
    return $key;
}

/**
 * 生成order
 * @return string
 */
function getOrderNum($head='CS')
{
    $order_num = $head."XHL" . date('Ymd') . mt_rand(10000, 99999) . time();
    return $order_num;
}

//获取季度时间范围
function getDataFanWei($season){
    return array(
        "s"=>date('Y-m-d H:i:s', mktime(0, 0, 0,$season*3-3+1,1,date('Y'))),
        "e"=>date('Y-m-d H:i:s', mktime(23,59,59,$season*3,date('t',mktime(0, 0 , 0,$season*3,1,date("Y"))),date('Y')))
    );
}


//判断html代码中是否含有IMG
function judgeHtml($str){
    if($str != strip_tags($str)){
        return true;
    }else{
        return false;
    }
}


//获取数组长度
function getArrLenght($arr){

    return count($arr);
}

//输出问题数组
function outQuestion($arr){
    $html="";
    for($i=0;$i<count($arr);$i++){
        $html=$html."&nbsp;".$arr[$i]['c_name'];
    }
    return $html;
}


//递归重组分类节点信息
function node_cat($node,$pid=0){
    $arr=Array();
    foreach($node as $v){
        if($v['s_parent']==$pid){
            $v['child']=node_cat($node,$v['id']);
            $arr[]=$v;
        }
    }
    sort($arr['c_order']);
    $arr=array_filter($arr);//过滤空数组
    return $arr;
}

//向页面输出json数据，$code状态码，$msg输出到前台的信息，$to跳转的页面
function outMsg($code=0,$msg="",$to=""){
    $dataResult=array(
        "code"=>$code,
        "msg"=>$msg,
        "to"=>$to
    );
    exit(json_encode($dataResult));
}

/**
 * 接口返回
 * @param int $code
 * @param string $msg
 * @param array $data
 */
function jsonReturn($code=0,$msg="",$data=[]){
    $dataResult=array(
        "status"=>$code,
        "msg"=>$msg,
        "data"=>$data
    );
    exit(json_encode($dataResult));
}

function replaceStar($str, $start, $length = 0)
{
    $i = 0;
    $star = '';
    if($start >= 0) {
        if($length > 0) {
            $str_len = strlen($str);
            $count = $length;
            if($start >= $str_len) {//当开始的下标大于字符串长度的时候，就不做替换了
                $count = 0;
            }
        }elseif($length < 0){
            $str_len = strlen($str);
            $count = abs($length);
            if($start >= $str_len) {//当开始的下标大于字符串长度的时候，由于是反向的，就从最后那个字符的下标开始
                $start = $str_len - 1;
            }
            $offset = $start - $count + 1;//起点下标减去数量，计算偏移量
            $count = $offset >= 0 ? abs($length) : ($start + 1);//偏移量大于等于0说明没有超过最左边，小于0了说明超过了最左边，就用起点到最左边的长度
            $start = $offset >= 0 ? $offset : 0;//从最左边或左边的某个位置开始
        }else {
            $str_len = strlen($str);
            $count = $str_len - $start;//计算要替换的数量
        }
    }else {
        if($length > 0) {
            $offset = abs($start);
            $count = $offset >= $length ? $length : $offset;//大于等于长度的时候 没有超出最右边
        }elseif($length < 0){
            $str_len = strlen($str);
            $end = $str_len + $start;//计算偏移的结尾值
            $offset = abs($start + $length) - 1;//计算偏移量，由于都是负数就加起来
            $start = $str_len - $offset;//计算起点值
            $start = $start >= 0 ? $start : 0;
            $count = $end - $start + 1;
        }else {
            $str_len = strlen($str);
            $count = $str_len + $start + 1;//计算需要偏移的长度
            $start = 0;
        }
    }

    while ($i < $count) {
        $star .= '*';
        $i++;
    }

    return substr_replace($str, $star, $start, $count);
}

//获取客户端IP
function getIp() {
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) $ip = getenv("HTTP_CLIENT_IP");
    else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) $ip = getenv("HTTP_X_FORWARDED_FOR");
    else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")) $ip = getenv("REMOTE_ADDR");
    else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")) $ip = $_SERVER['REMOTE_ADDR'];
    else $ip = "unknown";
    return ($ip);
}


// 计算两日期之间间隔
function DateDiff ($interval = "d", $date1,$date2) {
    $timedifference = strtotime($date2) - strtotime($date1);
    switch ($interval) {
        case "w": $retval = bcdiv($timedifference ,604800); break;//星期
        case "d": $retval = bcdiv( $timedifference,86400); break;//天
        case "h": $retval = bcdiv ($timedifference,3600); break;//小时
        case "n": $retval = bcdiv( $timedifference,60); break;//分钟
        case "s": $retval = $timedifference; break;//秒
    }
    return $retval;
}



//截取字符串
function sysSubStr($string,$length,$append = true)
{
    if(strlen($string) <= $length )
    {
        return $string;
    }
    else
    {
        $i = 0;
        while ($i < $length)
        {
            $stringTMP = substr($string,$i,1);
            if ( ord($stringTMP) >=224 )
            {
                $stringTMP = substr($string,$i,3);
                $i = $i + 3;
            }
            elseif( ord($stringTMP) >=192 )
            {
                $stringTMP = substr($string,$i,2);
                $i = $i + 2;
            }
            else
            {
                $i = $i + 1;
            }
            $stringLast[] = $stringTMP;
        }
        $stringLast = implode("",$stringLast);
        if($append)
        {
            $stringLast .= "...";
        }
        return $stringLast;
    }
}

/**
 * 对象转数组
 * @param object
 * @return array
 */
function object2array(&$object) {
    $object =  json_decode( json_encode( $object),true);
    return  $object;
}

/**
 * 数组转对象
 * @param array
 * @return object
 */
function arrayToObject($e){
    if( gettype($e)!='array' )
        return;
    foreach($e as $k=>$v){
        if( gettype($v)=='array' || getType($v)=='object' )
            $e[$k] = arrayToObject($v);
    }
    return (object)$e;
}


//是否包含关键词
function isHaveKeys($keys,$key){
    if(strstr($keys,$key)){
        echo 'checked="checked"';
    }
}

//格式化时间
function formartDate($formart,$date){
    return date($formart,strtotime($date));
}

function noDivHTML($content)
{

    $content = preg_replace("/<div[^>]*>/i",'', $content);
    $content = preg_replace("/<\/div>/i",'', $content);
    $content=str_replace( "&nbsp;","",$content);
    return $content;
}


function noHTML($content)
{
    $content = preg_replace("/<img[^>]*>/i",'', $content);
    $content = preg_replace("/<\/img>/i", '', $content);
    $content = preg_replace("/<a[^>]*>/i",'', $content);
    $content = preg_replace("/<\/a>/i", '', $content);
    $content = preg_replace("/<div[^>]*>/i",'', $content);
    $content = preg_replace("/<\/div>/i",'', $content);
    $content = preg_replace("/<font[^>]*>/i",'', $content);
    $content = preg_replace("/<\/font>/i",'', $content);
    $content = preg_replace("/<p[^>]*>/i",'', $content);
    $content = preg_replace("/<\/p>/i",'', $content);
    $content = preg_replace("/<span[^>]*>/i",'', $content);
    $content = preg_replace("/<\/span>/i",'', $content);
    $content = preg_replace("/<\?xml[^>]*>/i",'', $content);
    $content = preg_replace("/<\/\?xml>/i",'', $content);
    $content = preg_replace("/<o:p[^>]*>/i",'', $content);
    $content = preg_replace("/<\/o:p>/i",'', $content);
    $content = preg_replace("/<u[^>]*>/i",'', $content);
    $content = preg_replace("/<\/u>/i",'', $content);
    $content = preg_replace("/<b[^>]*>/i",'', $content);
    $content = preg_replace("/<\/b>/i",'', $content);
    $content = preg_replace("/<meta[^>]*>/i",'', $content);
    $content = preg_replace("/<\/meta>/i",'', $content);
    $content = preg_replace("/<!--[^>]*-->/i",'', $content);//注释内容
    $content = preg_replace("/<p[^>]*-->/i",'', $content);//注释内容
    $content = preg_replace("/style=.+?['|\"]/i",'',$content);//去除样式
    $content = preg_replace("/class=.+?['|\"]/i",'',$content);//去除样式
    $content = preg_replace("/id=.+?['|\"]/i",'',$content);//去除样式
    $content = preg_replace("/lang=.+?['|\"]/i",'',$content);//去除样式
    $content = preg_replace("/width=.+?['|\"]/i",'',$content);//去除样式
    $content = preg_replace("/height=.+?['|\"]/i",'',$content);//去除样式
    $content = preg_replace("/border=.+?['|\"]/i",'',$content);//去除样式
    $content = preg_replace("/face=.+?['|\"]/i",'',$content);//去除样式
    $content = preg_replace("/face=.+?['|\"]/",'',$content);
    $content = preg_replace("/face=.+?['|\"]/",'',$content);
    $content=str_replace( "&nbsp;","",$content);
    $content=strip_tags($content);
    $content = trim($content);// 首先去掉头尾空格
    $content = preg_replace('/\s(?=\s)/', '', $content);// 接着去掉两个空格以上的
    $content = preg_replace('/[\n\r\t]/', ' ', $content);// 最后将非空格替换为一个空格
    return $content;
}

//文本转义
function htmldecode($txt){
    return stripslashes($txt);
}


//判断两个字符串是否相等，用于辅助前台模板标签不足
function isEq($o1,$o2){
    if(empty($o1) || empty($o2)){
        return false;
    }
    if($o1==$o2){
        return true;
    }else{
        return false;
    }
}


//格式化时间
function forMatDate($time,$forMat="Y-m-d H:i:s"){
    $date=date($forMat,strtotime($time));
    return $date;
}

//获取系统时间
function getTime(){
    return date('Y-m-d H:i:s');
}


//自动给数组加上guid
function addGuidToArray($data){
    if(empty($data)){
        return $data;
    }
    $data["guid"]=create_guid();
    return $data;
}


//生成GUID
function create_guid() {
    $charid = strtoupper(md5(uniqid(mt_rand(), true)));
    $hyphen = chr(45);// "-"
    $uuid = chr(123)// "{"
        .substr($charid, 0, 8).$hyphen
        .substr($charid, 8, 4).$hyphen
        .substr($charid,12, 4).$hyphen
        .substr($charid,16, 4).$hyphen
        .substr($charid,20,12)
        .chr(125);// "}"
    return md5($uuid);
}


// 重组排序
function getList($cates){
    foreach ($cates as $cate) {
        $prefix = "";
        $c = count(explode('-', $cate['path']));
        for ($i=0; $i <$c ; $i++) {
            $prefix.="&nbsp;&nbsp;&nbsp;&nbsp;";
        }
        $cate['pre_name'] = $prefix.$cate['c_name'];
    }
    return $cates;
}

////获取年月
//function getYearAndMonth($date){
//    $pos = strpos($mystring, $findme);
//    return  subStr($date,0,4)."-".date("m",strtotime($date));
//}

//获取日期
function getDay($date){
    return date("d",strtotime($date));
}


//获取年月日周季
function timeCompute($time){
    if (!empty($time)) {
        $ymd               = date("Ymd", $time);
        $result['year']    = substr($ymd, 0, 4);
        $result['month']   = substr($ymd, 4, 2);
        $result['day']     = substr($ymd, 6, 2);
        $result['week']    = date('W', $time);
        $result['quarter'] = ceil($result['month'] / 3);
        return $result;
    } else {
        return FALSE;
    }
}

//时间段计算
function gainTime($sign, $num)
{
    //获取当前时间(返回时间戳)
    switch ($sign) {
        case 'week':
            //php获取本周周起始时间戳和结束时间戳
            $time = mktime(0, 0, 0, date('m'), date('d') - date('w') + 1 + ($num * 7), date('Y'));
            break;
        case 'month':
            $time  = mktime(0, 0, 0, date("m") + $num, 1, date("Y"));
            break;
        case 'day':
            //天的时间
            $time = mktime(0, 0, 0, date('m'), date('d')+$num, date('Y'));
            break;
        case 'quarter':
            //获取季度时间
            $quarter = ceil((date('n')) / 3) + $num;//上季度是第几季度
            $time = mktime(0, 0, 0, $quarter * 3 - 3 + 1, 1, date('Y'));
            break;
    }
    return $time;
}

function get_weeks_num($time){
    $month = intval(date('m',$time));//当前时间的月份
    $fyear = strtotime(date('Y-01-01',$time));//今年第一天时间戳
    $fdate = intval(date('N',$fyear));//今年第一天 周几
    $sysweek = intval(date('W',$time));//系统时间的第几周
    //大于等于52 且 当前月为1时， 返回1
    if(($sysweek >= 52 && $month == 1)){
        return 1;
    }elseif($fdate == 1){
        //如果今年的第一天是周一,返回系统时间第几周
        return $sysweek;
    }else{
        //返回系统周+1
        return $sysweek + 1;
    }
}

//生成6位纯数字随机验证码
function codeRange($length = 6){
    return str_pad(mt_rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
}


////发送短信
//function SendMsg($moblie,$param,$templateid = '271027'){
//    Loader::import('ucpaas\Ucpass', EXTEND_PATH);
//    $ucpass = new \ucpaas\SendMsg();
//    return $ucpass->sendMsg($moblie,$param,$templateid);
//}

//发送短信
function SendMsg($moblie,$param,$templateid = '2290616'){
    $arr = ['code'=>$param];
    Loader::import('yunpian\Yunpian', EXTEND_PATH);
    $yunpian = new  \yunpian\Yunpian();
    $GB = '/^(\+?44|0)7\d{9}$/';
    $CN = '/^(\+?0?86\-?)?1[345789]\d{9}$/';
    if (preg_match($GB,$moblie)){
        $moblie = '+44'.$moblie;
    }elseif(preg_match($CN,$moblie)){
        $moblie = '+86'.$moblie;
    }
    return $yunpian->tpl_send($arr,$moblie,$templateid);
}


//创建订单号
function createOrderNo(){
    return 'NO.'.date("YmdHis"). mt_rand(10000, 99999);
}

//分离日期和时间节点
function partDate($date){
    $is_date=strtotime($date)?strtotime($date):false;
    if($is_date===false){
        $timeArr['date'] = ''; //日期
        $timeArr['time'] = ''; //时间
        return $timeArr;
    }else {
        $timeArr = [];
        $time = strtotime($date);
        $timeArr['date'] = date("Y-m-d", $time); //日期
        $timeArr['time'] = date("H:i:s", $time); //时间
        return $timeArr;
    }
}
